from typing import Optional
from fastapi import APIRouter, UploadFile, File, Form, Body
from pydantic import BaseModel

from services.file.file_service import FileService

router = APIRouter(prefix="/file", tags=["文件上传"])
file_service = FileService()

@router.post("/upload")
async def upload_file(
    file: UploadFile = File(...)
):
    """
    文件上传接口：上传文件，返回 file_id
    """
    file_id = await file_service.upload_file(file)
    return {"code": 200, "message": "上传成功", "data": {"file_id": file_id}}

@router.get("/upload/progress/{file_id}")
def get_upload_progress(file_id: str):
    """
    查询上传/分析进度
    """
    progress = file_service.get_upload_progress(file_id)
    return {"code": 200, "data": progress}

@router.post("/analyze")
async def analyze_file(
    file_id: str = Form(...),
    extract_keywords: Optional[bool] = Form(True),
    generate_summary: Optional[bool] = Form(True),
    identify_structure: Optional[bool] = Form(True),
    docKeyExtraction: Optional[str] = Form(None)
):
    """
    文档分析接口（流式SSE返回进度和结果）
    """
    options = {
        "extract_keywords": extract_keywords,
        "generate_summary": generate_summary,
        "identify_structure": identify_structure,
        "docKeyExtraction": docKeyExtraction
    }
    return await file_service.analyze_file(file_id, options)

@router.post("/extract-chapters")
async def extract_chapters(
    file_id: str = Form(...)
):
    """
    获取章节信息接口（流式SSE返回进度和结果）
    """
    return await file_service.extract_chapters(file_id)

@router.delete("/cleanup/{file_id}")
async def cleanup_file(file_id: str):
    """
    清理文件接口：手动清理指定文件及其缓存
    """
    file_service.cleanup_file(file_id)
    return {"code": 200, "message": "文件清理成功"}

class CodeExampleRequest(BaseModel):
    title: str